package com.gxp.util.security;

import java.io.IOException;
import java.net.URLDecoder;

import javax.crypto.Cipher;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.codec.binary.Hex;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;


public class RSAFilter extends HttpServlet implements Filter {
	Logger logger = Logger.getLogger(RSAFilter.class);

	
	static class FilteredRequest extends HttpServletRequestWrapper {

    	public FilteredRequest(ServletRequest request) {
    		super((HttpServletRequest)request);
    	}


    	public String getParameter(String paramName) {
    		System.out.println("get param name: " + paramName);
    		if ("j_password".equals(paramName) || "password".equals(paramName) || "newPassword".equals(paramName) || "oriPassword".equals(paramName)) {
    			try {
    				System.out.println("~~~~~~~~~~~~encrypted pwd: " + super.getParameter("j_encrypted_pwd"));
    				System.out.println("~~~~~~~~~~~~uncrypted pwd: " + decodeTry(super.getParameter("j_encrypted_pwd")));
					return decodeTry(super.getParameter("j_encrypted_pwd"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    		return super.getParameter(paramName);
    	}
    }
	/**
	 * 
	 */
	private static final long serialVersionUID = -2941335028732367420L;
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		
		filterChain.doFilter(new FilteredRequest(request), response);
	}
	

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	
	/**  
     *   
     */  
    private static String decodeTry(String res) throws Exception {  
        Cipher cipher = Cipher.getInstance("RSA",new BouncyCastleProvider());//必须指定此提供者  
        cipher.init(Cipher.DECRYPT_MODE, RSAUtil.getInstance().getPrivateKey());  
        System.out.println(res);  
        byte[] buff = cipher.doFinal(Hex.decodeHex(res.toCharArray()));  
        //将字符串转为字符  
        StringBuilder sb = new StringBuilder(new String(buff,"UTF-8"));  
        //解密后的内容是倒叙的  
        sb.reverse();  
        //进行URL解密，主要是为了中文乱码问题  
        String result = URLDecoder.decode(sb.toString(), "UTF-8");  
        return result;
    }  
}
